package com.dana1.nos;

import java.util.ConcurrentModificationException;

import junit.framework.Assert;

import org.junit.Before;
import org.junit.Test;

import com.dana1.nos.storage.MemoryStorage;

public class TestMemoryStorage {

	transient Storage storage;
	
	
	@Before
	public void setup()
	{
		storage = new MemoryStorage();
	}
	
	@Test
	public void testStandardGetPut() {

		StringBuilder sa = new StringBuilder("This is a test");
		
		storage.put("a", sa);

		StringBuilder sb = storage.get(StringBuilder.class,"a");
		
		Assert.assertEquals("This is a test", sb.toString());
		Assert.assertNotSame(sa,sb);

		storage.remove(sa);
		
		storage.put("a", sa); // insert works after remove?

		storage.put(null, sa.reverse()); // null identifier should be ok, once object is recognized
		 
	}

	@Test(expected=ConcurrentModificationException.class)
	public void testConcurrencyFail() {

		StringBuilder sa = new StringBuilder("This is a test");
		
		storage.put("a", sa);

		StringBuilder sb = storage.get(StringBuilder.class,"a");
		
		storage.put("a", sa.reverse());
		
		storage.put("a", sb.reverse()); // same string, but now not the most recent copy
		
	}

	@Test(expected=IllegalArgumentException.class)
	public void testIdentChangeFails()
	{
		StringBuilder sa = new StringBuilder("This is a test");
		
		storage.put("a", sa);
		
		storage.put("b", sa);
	}

	@Test(expected=ConcurrentModificationException.class)
	public void testDuplicateRemoveFails()
	{
		StringBuilder sa = new StringBuilder("This is a test");
		
		storage.put("a", sa);
		
		StringBuilder sb = storage.get(StringBuilder.class, "a");

		storage.remove(sa);
		
		storage.remove(sb);
	}
}
